<template>
  <div>

    <!--    新建教师-->
    <el-button type="primary" @click="openDialogClick">+ 新建</el-button>
    <el-select v-model="searchByTeacherId" placeholder="选择教师" :disabled="searchByTeacherDisable">
      <el-option
        v-for="item in selectTeacherList"
        :key="item.lxUserId"
        :label="item.lxUsername"
        :value="item.lxUserId">
      </el-option>
    </el-select>
    <el-input
      style="width: 220px;margin-left: 20px"
      placeholder="请输入考勤名"
      v-model="searchByNameKeyword"
      prefix-icon="el-icon-search"

      clearable>
    </el-input>
    <el-button type="primary" plain @click="searchBtnClick">查询</el-button>
    <el-button type="success" plain @click="searchResetBtnClick">重置</el-button>
    <div style="margin: 20px 0;"></div>
    <!--新建表单-->
    <el-dialog title="新建考勤" :visible.sync="dialogFormVisible"  :close-on-click-modal='false' :show-close="false">
      <el-form :model="checkworkForm" :rules="rules" ref="checkworkForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="考勤发布名" prop="lxCheckWorkName">
          <el-input v-model="checkworkForm.lxCheckWorkName" :clearable="true"></el-input>
        </el-form-item>
        <el-form-item label="发布人" prop="lxUsername">
          <el-input v-model="checkworkForm.lxUsername" disabled></el-input>
        </el-form-item>
        <el-form-item label="时效" prop="lxCheckAging">
          <el-select v-model="checkworkForm.lxCheckAging"  placeholder="请选择考勤有效时间">
            <el-option
              v-for="item in times"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择班级" prop="lxClazzId">
          <el-select v-model="checkworkForm.lxClazzId" multiple placeholder="请选择考勤班级">
            <el-option
              v-for="item in selectClazzList"
              :key="item.id"
              :label="item.lxClazzName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间" prop="lxReleaseTime">
          <el-input v-model="checkworkForm.lxReleaseTime" disabled placeholder="此处不可输入，发布后自动更新"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('checkworkForm')">保存</el-button>
          <el-button @click="resetForm('checkworkForm')">取消</el-button>
        </el-form-item>
      </el-form>
      <!--        <div slot="footer" class="dialog-footer">-->
      <!--          <el-button @click="dialogFormVisible = false">取 消</el-button>-->
      <!--          <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>-->
      <!--        </div>-->
    </el-dialog>

    <el-dialog ref="tk" title="二维码" :visible.sync="dialogQRVisible"  :close-on-click-modal='false' :show-close="false" width="800">
      <div style="height:500px;width:450px;  overflow: auto;float:left;margin-right: 20px">
        <img :src="verifyCode">
      </div>
      <div style="float: left;margin-top: 30px">
        <h1 style="font-size: 40px;width: 100%;text-align: center">签到剩余时间</h1>
        <h1 style="color: red;font-size: 40px;width: 100%;text-align: center">
          {{min}}分钟 {{sec}}秒
        </h1>
        <el-button type="danger" plain size="medium" style="width: 100%" @click="endDaka">结束签到</el-button>
      </div>


    </el-dialog>


    <!--考勤发布列表-->
    <el-table
      ref="multipleTable"
      border
      :data="checkworkList"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">

      </el-table-column>
      <el-table-column
        prop="date"
        label="序号"
        width="60">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        prop="lxCheckWorkName"
        label="考勤发布名"
        width="250">
      </el-table-column>
      <el-table-column
        prop="lxUsername"
        label="发布人" width="100">
      </el-table-column>
      <el-table-column
        prop="lxClazzName"
        label="考勤班级" width="300">
      </el-table-column>
      <el-table-column
        prop="lxCheckAging"
        label="时效  (分钟)" >
      </el-table-column>
      <el-table-column
        prop="lxReleaseTime"
        label="发布时间" width="180">
      </el-table-column>

      <el-table-column
        label="操作"
        width="200">
        <template slot-scope="scope">
          <router-link :to="{ name: '/checkwork/checkworkResult', params: { lxCheckworkId: scope.row.id }}">
            <el-button  type="warning" size="small">查看考勤结果</el-button>
          </router-link>

          <el-button @click="handleDeleteClick(scope.row)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="bottom" style="margin-bottom: 0;margin-top: 10px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentPageChange"
        :current-page="currentPage"
        :page-sizes="[8, 10, 20, 40]"
        :page-size="pagesize"
        :background='true'
        :pager-count="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total" class="pageControl">
      </el-pagination>
    </div>


  </div>
</template>

<script>
export default {
  name: "UserTeacher",
  data(){
    return{
      verifyCode:'',
      currentPage:1,
      pagesize:8,
      total:0,
      pageNum:1,
      searchByNameKeyword:'',
      searchByTeacherId:'',
      search:false,
      day:'',
      hr:'',
      min:'',
      sec:'',
      end : '',
      timeMessage:'',
      searchByTeacherDisable:true,
      checkworkList:[
        // {
        //   id:'',
        //   lxUserId:'',
        //   lxUsername:'',
        //   lxCheckWorkName:'',
        //   lxCheckAging:'',
        //   lxClazzId:'',
        //   lxClazzName:'',
        //   lxReleaseTime:'',
        // }
      ],
      selectTeacherList:[],
      selectClazzList:[
        //   {
        //   id:'',
        //   lxClazzName:'',
        //   lxTeacher:"",
        //   lxTeacherName:'',
        //   lxClazzPeopleNum:'',
        // }
      ],
      lxUser: {
            id:'',
          lxUserId: '',
          lxUserNumber:'',
          lxUsername:'',
          lxUserSex:'',
          lxUserPhone:'',
        }
      ,
      times: [
        {
        value: '1',
        label: '1分钟'
      }, {
        value: '2',
        label: '2分钟'
      }, {
        value: '3',
        label: '3分钟'
      }, {
        value: '5',
        label: '5分钟'
      }, {
        value: '8',
        label: '8分钟'
      }
      ],
      clazzIds:[],
      checkworkForm:{
        id:'',
        lxUserId:'',
        lxUsername:'',
        lxCheckWorkName:'',
        lxCheckAging:'',
        lxClazzId:'',
        lxReleaseTime:'',
      },
      dialogSelectClazzVisible:false,
      dialogQRVisible:false,
      checkworkFormInit:{
        id:'',
        lxUserId:'',
        lxUsername:'',
        lxCheckWorkName:'',
        lxCheckAging:'',
        lxClazzId:'',
        lxReleaseTime:'',
      },

      dialogFormVisible:false,
      innerVisible: false,  //选择学生
      innerClazzVisible:false, //选择办积极
      rules: {  //表单验证规则
        lxUserId: [
          {required: true, message: '请选择学生', trigger: 'blur'},
        ],
        lxUsername: [
          {required: true, message: '请输入发布人姓名', trigger: 'blur'},
        ],
        lxCheckWorkName: [
          {required: true, message: '请输入考勤发布名', trigger: 'blur'},
        ],
        lxCheckAging: [
          {required: true, message: '请输入考勤有效时间', trigger: 'blur'}
        ],
        lxClazzId: [
          {required: true, message: '请选择考勤班级', trigger: 'blur'}
        ],
        lxClazzName: [
          {required: false, message: '请输入考勤有效时间', trigger: 'blur'}
        ],
        lxReleaseTime: [
          {required: false, message: '请选择班级', trigger: 'blur'}
        ],
      },

      lxCheckAging:'',
      checkId:'',
    }


  },
  mounted() {
    this.$emit('getMessage', ["考勤管理","考勤发布"]);
    this.load();
  },
  methods:{
    load(){
      var userid=sessionStorage.getItem("LoginName");
      if(this.search){
        console.log("queryBykey")
        this.searchBtnClick()
      }else {
        console.log("queryAll")
        this.$http.get('/checkwork/index',{params:{currentPage:this.currentPage,pagesize:this.pagesize,id:userid}}).then(res=>{
          console.log("this.currentPage",this.currentPage)
          this.checkworkList=res.data.data.records;
          this.total=res.data.data.total;
          this.pageNum=res.data.data.pageNum;
          console.log("this.checkworkList",res)
          console.log("this.checkworkList",this.checkworkList)
        });
      }

      this.$http.post('/user/queryById',userid).then(res => {
        this.lxUser = res.data.data;
        if (this.lxUser.lxRoleId==1)
          this.searchByTeacherDisable=false
        console.log("/user/queryById", res)

      });
      this.$http.post('/clazz/selectTeachers').then(res => {
        this.selectTeacherList = res.data.data;
        console.log("selectTeacherList", res)
      });
      this.$http.get('/clazz/queryByTeacherPage',{params:{currentPage:1,pagesize:20,id:sessionStorage.getItem("LoginName")}}).then(res => {
        this.selectClazzList=res.data.data.records;
        console.log("/clazz/queryByTeacherPage", res)
        console.log("this.selectClazzList", this.selectClazzList)
      });

    },//load结束
    handleSizeChange:function(size){
      //选择 一页展示多少数据时 调用的方法
      this.pagesize = size;
      console.log(size+"****");
      this.currentPage=1;
      this.load()
    },
    handleCurrentPageChange:function(currentPage){
      //点击页面项 的函数响应
      this.currentPage = currentPage;
      console.log("this.currentPage = currentPage;",this.currentPage)
      this.load()
    },
    searchBtnClick(){ //根据条件查询
      console.log("searchBtnClisk",this.searchByClass,this.searchByNameKeyword)
      this.search=true;
      if (this.searchByTeacherId!=''){
        console.log("searchBtnClisk searchByName")
        this.$http.post('/checkwork/queryCheckByTeacherPage',{params:{currentPage:this.currentPage,pagesize:this.pagesize,id:this.searchByTeacherId}}).then(res => {
          this.checkworkList=res.data.data.records;
          this.total=res.data.data.total;
          this.pageNum=res.data.data.pageNum;
          console.log("res", res)
          console.log("this.studentList", this.checkworkList)
        });

      }else if(this.searchByNameKeyword!=null&&this.searchByNameKeyword!=''&&this.searchByTeacherId==''){
        console.log("searchBtnClisk queryByKeyword")

        this.$http.get('/checkwork/queryByKeyword',{params:{currentPage:this.currentPage,pagesize:this.pagesize,keyword:this.searchByNameKeyword}}).then(res => {

          this.checkworkList=res.data.data.records;
          this.total=res.data.data.total;
          this.pageNum=res.data.data.pageNum;
          console.log("res", res)
          console.log("this.studentList", this.checkworkList)
        });
      }else{
        console.log("searchBtnClisk is null")
      }

    },searchResetBtnClick(){  //重置搜索条件
      this.searchByTeacherId=''
      this.searchByNameKeyword="";
      this.currentPage=1
      this.search=false;
      this.load()
    },
    handleSelectClazz(){  //选择考勤班级

    },
    openDialogClick(){
      this.dialogFormVisible=true
      var lxUserId=sessionStorage.getItem("LoginName")
      this.$http.post('/user/queryById',lxUserId).then(res => {
        this.lxUser = res.data.data;
        this.checkworkForm.lxUserId=this.lxUser.id;
        this.checkworkForm.lxUsername=this.lxUser.lxUsername
        console.log("/user/queryById", res)

      });
    },
    getQRCode(checkId){
      console.log("/weChat/getCode checkId",checkId)
      this.checkId=checkId
      this.$refs.tk.$el.firstChild.style.height = '70%';
      let url='/weChat/getCode?checkId='+checkId
      var that = this
      this.$http.get(url, {
          responseType: "arraybuffer",
          timeout:2000
        })
        .then(response => {
          return (
            "data:image/png;base64," +
            btoa(
              new Uint8Array(response.data).reduce(
                (data, byte) => data + String.fromCharCode(byte),
                ""
              )
            )
          );
        })
        .then(data => {
          this.verifyCode = data; //赋值给img标签的src属性
        });
      this.dialogQRVisible=true;
      this.end=Date.parse(new Date())+this.lxCheckAging*1000*60
      console.log("this.lxCheckAging",this.lxCheckAging)
      this.countdown()

    },
    endDaka(){  //考勤结束按钮
      this.$confirm('此操作将立即结束当前考勤，并将未签到的学生全部判定为缺勤, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("/checkwork/stopSignin",this.checkId)
        this.$http.post('/checkwork/stopSignin',this.checkId).then(res=>{
          console.log("/checkwork/stopSignin res",res)
          if (res.data.state==200){
            this.dialogQRVisible=false;
            this.$message({
              type: 'success',
              message: '操作成功!'
            });

          }else {
            this.$message.error('操作失败');
          }
          this.load();
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    submitForm(checkworkForm) {  //添加/更新表单
      this.$refs[checkworkForm].validate((valid) => {
        if (valid) {
          console.log("checkworkForm",this.checkworkForm);
          let str=this.checkworkForm.lxClazzId.join(",")
          this.checkworkForm.lxClazzId=str;
          console.log("checkworkForm Str",this.checkworkForm);
          this.lxCheckAging=this.checkworkForm.lxCheckAging;
          console.log("/checkwork/addCheckwork lxCheckAging:",this.checkworkForm.lxCheckAging)
          this.$http.post('/checkwork/addCheckwork',this.checkworkForm).then(res=>{
            console.log("/checkwork/addCheckwork res",res)
            if (res.data.state==200){
              let checkId = res.data.data;
              this.getQRCode(checkId)
              this.$refs[checkworkForm].resetFields();
              setTimeout(this.$message({
                message: '操作成功',
                type: 'success'
              }),1000)

            }else {
              this.$message.error('操作失败');
            }
            this.load();
          });

          this.closeDialog()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(checkworkForm) {
      this.$refs[checkworkForm].resetFields();
      this.closeDialog()
    },
    closeDialog(){
      this.checkworkForm= {...this.checkworkFormInit}
      this.dialogFormVisible=false
    },

    updateClick(rows){  //编辑教师
      console.log("updateClick",rows)
      this.checkworkForm={...rows};
      console.log("updateClick,checkworkForm",this.checkworkForm)
      this.dialogFormVisible=true;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleDeleteClick(rows){  //根据id删除教师
      console.log("delete rows",rows);
      var id=rows.id
      this.$confirm('此操作将永久删除该考勤信息，并且删除与此相关的学生签到信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("postid",id)
        this.$http.post('/checkwork/deleteCheckwork',id).then(res=>{
          console.log("res",res)
          this.load()
          if (res.data.state==200){ //成功删除弹窗
            setTimeout(this.$message({
              type: 'success',
              message: '删除成功!'
            }),1000)
          }else {
            this.$message.error('删除失败！');
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    countdown(stop) {

      try{
        if(stop==1){
          this.end=Date.parse(new Date())+1*1000;

        }
        const now = Date.parse(new Date())
        const msec = this.end - now
        console.log("msec",msec)


        let day = parseInt(msec / 1000 / 60 / 60 / 24)
        let hr = parseInt(msec / 1000 / 60 / 60 % 24)
        let min = parseInt(msec / 1000 / 60 % 60)
        let sec = parseInt(msec / 1000 % 60)
        this.day = day
        this.hr = hr > 9 ? hr : '0' + hr
        this.min = min > 9 ? min : '0' + min
        this.sec = sec > 9 ? sec : '0' + sec
        const that = this
        if(min>=0 && sec>=0){
          //倒计时结束关闭订单
          if(min==0 && sec==0||stop==1){
            console.log("TIMEOUT");
            this.timeMessage="timeout";
            throw new Error("ending")

          }
          setTimeout(function () {
            that.countdown()
          }, 1000)
        }
      }catch (e) {
        console.log("catch");
      }
    },

  },




}
</script>

<style scoped>


</style>
